package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.CaretakerClientDAO;
import com.neusoft.EYSystem.dao.ClientDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.CaretakerClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CaretakerClientServiceImpl implements CaretakerClientService {

    // ✅ 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }


    @Autowired
    private CaretakerClientDAO caretakerClientDAO;

    @Autowired
    private ClientDAO clientDAO;

    @Override
    public PageResponseBean<List<Client>> getIncludedClients(Long cur, Long number, Client client, User user) {
        PageResponseBean<List<Client>> response;
        try {
            // 0. 查询 link 表中当前用户的所有客户Id
            QueryWrapper<CaretakerClient> linkWrapper = new QueryWrapper<>();
            linkWrapper.eq("caretaker_id", user.getUserId());
            linkWrapper.eq("is_servered", 1);
            List<CaretakerClient> links = caretakerClientDAO.selectList(linkWrapper);

            if (links.isEmpty()) {
                return new PageResponseBean<>(List.of()); // 当前用户没有任何关联客户，返回空列表
            }

            // 1. 提取所有 客户Id
            List<Integer> clientIds = links.stream().map(CaretakerClient::getClientId).toList();

            // 2. 分页查询表
            IPage<Client> page = new Page<>(cur, number);
            QueryWrapper<Client> clientWrapper = new QueryWrapper<>();
            clientWrapper.in("client_id", clientIds);

            // 3. 拼接模糊查询条件（项目名、状态）
            if (isValid(client.getName())) {
                clientWrapper.like("name", client.getName());
            }

            IPage<Client> result = clientDAO.selectPage(page, clientWrapper);

            // 4. 封装结果
            List<Client> list = result.getRecords();
            long total = result.getTotal();
            response = new PageResponseBean<>(list);
            response.setTotal(total);
        } catch (Exception e) {
            e.printStackTrace();
            response = new PageResponseBean<>(500, "查询用户已包含客户失败");
        }

        return response;
    }

    @Override
    public PageResponseBean<List<Client>> getExcludedClients(Long cur, Long number, Client client, User user) {
        PageResponseBean<List<Client>> response;
        try {
            // 0. 查询 link 表中所有用户的所有客户Id
            QueryWrapper<CaretakerClient> linkWrapper = new QueryWrapper<>();
            linkWrapper.eq("is_servered", 1);
            List<CaretakerClient> links = caretakerClientDAO.selectList(linkWrapper);

            // 2. 分页查询表
            IPage<Client> page = new Page<>(cur, number);
            QueryWrapper<Client> clientWrapper = new QueryWrapper<>();


            if (links.isEmpty()) {
            } else{
                // 1. 提取所有 客户Id
                List<Integer> clientIds = links.stream().map(CaretakerClient::getClientId).toList();
                clientWrapper.notIn("client_id", clientIds);
            }

            // 3. 拼接模糊查询条件（项目名、状态）
            if (isValid(client.getName())) {
                clientWrapper.like("name", client.getName());
            }

            IPage<Client> result = clientDAO.selectPage(page, clientWrapper);

            // 4. 封装结果
            List<Client> list = result.getRecords();
            long total = result.getTotal();
            response = new PageResponseBean<>(list);
            response.setTotal(total);
        } catch (Exception e) {
            e.printStackTrace();
            response = new PageResponseBean<>(500, "查询用户已包含客户失败");
        }

        return response;

    }

    @Transactional
    @Override
    public ResponseBean<Integer> removeClientFromUser(Client client, User user) {
        ResponseBean<Integer> response = new ResponseBean<>();

            UpdateWrapper<CaretakerClient> wrapper = new UpdateWrapper<>();
            wrapper.eq("caretaker_id", user.getUserId())
                    .eq("client_id", client.getClientId());
            CaretakerClient caretakerClient = new CaretakerClient();
            caretakerClient.setIsServered(false);
            int deleted = caretakerClientDAO.update(caretakerClient,wrapper);

            if (deleted > 0) {
                // 更新 Client 的 userId 字段为 null
                Client clientToUpdate = clientDAO.selectById(client.getClientId());
                clientToUpdate.setUserId(null);
                clientDAO.updateById(clientToUpdate);
                response.setStatus(200);
                response.setMsg("护工移除客户成功");
            } else {
                response.setStatus(400);
                response.setMsg("护理级别移除护理项目失败，记录不存在");
            }
        return response;
    }
}
